package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.contants.ComContants;
import com.xxl.job.executor.dto.ResultDto;
import com.xxl.job.executor.model.BasTradeImport;
import com.xxl.job.executor.service.TradeImportService;
import com.xxl.job.executor.util.ExcelReader;
import com.xxl.job.executor.util.FTPUtil;
import com.xxl.job.executor.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZYZ
 * @DateTime: 2020/3/5 15:41
 * @Description:
 */
@Component
public class TradeImportJob {

    @Autowired
    private FTPUtil ftpUtil;

    @Autowired
    TradeImportService tradeImportService;

    @Value("${ftp.local.save.basepath}")
    private String localSavePath;

    private final String FILE_DIR = "sycm";

    @XxlJob("TradeImportAutoHandler")
    public ReturnT<String> TradeImportAutoHandler(String param) throws Exception {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            XxlJobLogger.log("开始从FTP服务器下载excel文件...");
            //先下载ftp上的所有文件
            Map<String, Object> fileMap = ftpUtil.downLoadTableFile(FILE_DIR, localSavePath, ComContants.EXCEL_KF);

            XxlJobLogger.log("开始遍历本地文件{}/{}", localSavePath, FILE_DIR);
            //遍历本地文件进行处理
            List<String> fileNameList = FileUtil.getFileNames(localSavePath + "/" + FILE_DIR);

            if (null != fileNameList && fileNameList.size() > 0) {
                for (String fileName : fileNameList) {
                    XxlJobLogger.log("开始解析文件名： {} ，判断店铺和类型的合法性.", fileName);
                    String[] strArr = fileName.split("_");
                    if (strArr.length > 1) {
                        if (ComContants.EXCEL_KF.equals(strArr[1])) {
                            String shopId = strArr[0];
                            if (tradeImportService.checkShopId(shopId)) {
                                String fileLocalPath = localSavePath + "/" + FILE_DIR + "/" + fileName;
                                XxlJobLogger.log("开始解析本地文件： {} ，转化excel文件为List<BasTradeImport>,忽略前{}行",
                                        fileLocalPath, 5);
                                //开始执行文件解析和导入
                                List<BasTradeImport> list = ExcelReader.readExcel(fileLocalPath, 5, BasTradeImport.class);

                                if (null != list && list.size() > 0) {

                                    XxlJobLogger.log("开始判断导入数据是否已经存在(bas_tradeImport)，shopId:{}，importDate:{} ", shopId, list.get(0).getMakeDate());
                                    Date queryDate = df.parse(list.get(0).getMakeDate());
                                    int count = tradeImportService.queryTradeRepition(shopId, queryDate);
                                    if (count == 0) {
                                        XxlJobLogger.log("开始执行导入，size： {} ", list.size());
                                        ResultDto result = tradeImportService.insertTradeImportNew(list, shopId);
                                    } else {
                                        XxlJobLogger.log("该日期数据已经存在，不执行导入");
                                    }
                                } else {
                                    XxlJobLogger.log("转化的List<BasTradeImport> 长度为0，不执行导入 ");
                                }
                                //执行服务器文件备份
                                XxlJobLogger.log("开始执行FTP服务器文件备份:{}/{} ", FILE_DIR, fileName);
                                ftpUtil.renameFile(FILE_DIR, fileName);
                                //删除本地文件
                                XxlJobLogger.log("开始删除本地服务器文件:{}  ", fileLocalPath);
                                FileUtil.removeFile(fileLocalPath);
                                //延迟执行下一个文件
                                XxlJobLogger.log("执行完毕，等待10s执行下一个文件导入");
                                Thread.sleep(10 * 1000);
                            } else {
                                XxlJobLogger.log(" 店铺ID 【{}】 无效，不执行导入 ", shopId);
                            }

                        } else {
                            XxlJobLogger.log(" 文件类型 【{}】 无效，不执行导入。正确类型应为 【{}】 ", strArr[1], ComContants.EXCEL_KF);
                        }
                    }

                }

            } else {
                XxlJobLogger.log(" 本地文件个数为0，不执行导入 ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ReturnT.SUCCESS;
    }
}
